package com.winit.select.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.base.web.BaseController;
import com.winit.select.service.SelectService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Api(value = "select", tags = {"select"}, description = "select")
@RestController
@RequestMapping("/api/v1/select")
public class SelectController extends BaseController {

    private static Logger log = LoggerFactory.getLogger(SelectController.class);

    @Autowired
    SelectService service;

    @RequestMapping(value = "/get", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "查询下拉列表数据")
    @ResponseBody
    public Map get(@ApiParam(value = "下拉列表类型。BRD_SOURCE, BRD_BUSINESS, BRD_ADD_GROSS_PROFIT, BRD_NEW_PIPELINE, BRD_IS_AFFECT_DR,\n" +
            "    BRD_BREAKDOWN_AFFECT, BRD_AFFECT_KPI, BRD_OTHER_AFFECT, BRD_TASK_LEVEL, BRD_ONLINE_MONTH,\n" +
            "    BRD_DEPARTMENT_CONFIRMED, BRD_IS_WITH_TRAIN, BRD_UAT, BRD_STATUS, BRD_RELATE, BRD_PRD_IS_CONFIRM", required = true) @RequestParam(value = "type", required = true) String type) {
        String code = BaseController.REQUEST_SUCCESS;
        Map map = service.getSelectConfigs(type);
        return this.getRtn(code, "", map);
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    @ApiOperation(value = "保存")
    @ResponseBody
    public Map save(@ApiParam(value = "type", required = true) @RequestParam(value = "type", required = true) String type,
                    @ApiParam(value = "列表的 tostring", required = true) @RequestParam(value = "list", required = true) String list) {
        JSONArray array = JSONArray.parseArray(list);
        Map map = new HashMap();
        for (int i = 0; i < array.size(); i++) {
            JSONObject object = array.getJSONObject(i);
            StringBuffer key = new StringBuffer();
            if (!StringUtils.isEmpty(object.getString("index"))) {
                key.append(object.getString("index")).append("@@@");
            }
            key.append(object.getString("key"));
            map.put(key.toString(), object.getString("value"));
        }
        service.saveSelectConfig(type, map);
        return this.getRtn(BaseController.REQUEST_SUCCESS, "");
    }

}
